<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: LanguageController.php 259 2011-07-22 08:44:00Z beimuaihui $
 */

function sum($array, $key, $filter = array(), $include_rule = false) {
	$total = 0;
	foreach ( $array as $row ) {
		$flag = true;
		foreach ( $filter as $k_filter => $v_filter ) {
			if (! $include_rule && strpos ( $k_filter, "rule_id_" ) !== false) {
				continue;
			}
			if ($row [$k_filter] != $v_filter) {
				$flag = false;
				break;
			}
		}
		if ($flag) {
			$total = $total + $row [$key];
		}
	}
	return $total;
}

class Qa_QasurveyController extends Baogg_Controller_Action {
	
	var $Qa_Questions;
	var $Qa_Answers;
	var $QaReport;
	var $Qa_Surveys;
	var $QaSurveys;
	
	function init() {
		$this->Qa_Questions = new Qa_Questions ();
		$this->Qa_Answers = new Qa_Answers ();
		$this->QaReport = new QaReport ();
		$this->Qa_Surveys = new Qa_Surveys ();
		$this->QaSurveys = new QaSurveys ();
		
		$params = $this->getRequest ()->getParams ();
		isset ( $params ['qa_report_id'] ) or die ( 'No report params' );
		$rs_qa_report = $this->QaReport->getOne ( $params ['qa_report_id'] );
		// check permission
		$User = new User ();
		if (! $User->isAdmin () && ! isset ( $_SESSION ['admin'] ['permission'] ['qa_surveys_id'] [$rs_qa_report [0] ['qa_surveys_id']] )) {
			echo BAOGG_LANGUAGE::get ( 'deny_access' );
			exit ();
		}
	
	}
	
	public function list2Action() {
		global $LANG;
		
		$params = $this->getRequest ()->getParams ();
		$post = $this->getRequest ()->getPost ();
		
		isset ( $params ['qa_report_id'] ) or die ( 'No report params' );
		$chart_url = $form_url = $params;
		
		Zend_Loader::loadClass ( "Baogg_View_Extgrid" );
		Baogg_Language::loadFile ( 'qaquestion' );
		Baogg_Language::loadFile ( 'brandrule' );
		
		$Rule = new Rule ();
		
		$rs_qa_report = $this->QaReport->getOne ( $params ['qa_report_id'] );
		$arr_qa_field_ids = explode ( ',', $rs_qa_report [0] ['qa_field_ids'] );
		$arr_qa_brand_ids = explode ( ',', $rs_qa_report [0] ['qa_brand_ids'] );
		$arr_qa_rule_ids = explode ( ',', $rs_qa_report [0] ['qa_rule_ids'] );
		$qa_surveys_id = $rs_qa_report [0] ['qa_surveys_id'];
		
		// filter brand,rule
		
		$rs_qasureys = $this->QaSurveys->getOne ( $qa_surveys_id );
		$sid = $rs_qasureys [0] ['sid'];
		
		$QaField = new QaField ();
		// get all fields
		$arr_field = $QaField->getArray ( array ('qa_surveys_id' => $qa_surveys_id, 'qa_field_id' => $arr_qa_field_ids ), array ('sort' => 'ordering', 'dir' => 'asc' ) );
		
		$QaBrand = new QaBrand ();
		$arr_qa_brand = $QaBrand->getList ( array ('qa_surveys_id' => $qa_surveys_id, 'qa_brand_id' => $arr_qa_brand_ids ), array ('sort' => 'ordering', 'dir' => 'asc' ) );
		
		$QaRule = new QaRule ();
		$arr_qa_rule = $QaRule->getList ( array ('qa_surveys_id' => $qa_surveys_id, 'qa_rule_id' => $arr_qa_rule_ids ), array ('sort' => 'ordering', 'dir' => 'asc' ) );
		
		$this->view->LANG = Zend_Json::encode ( $LANG );
		
		$form_url ['action'] = 'data2';
		$form = new Baogg_View_Extform ( array ("url" => $form_url ), array (), array ('maximized' => true ) );//, 'renderTo' => 'myForm'
		
		$arr_sql_filter ['basic_info'] = array ('id' => 'basic_info', 'fieldLabel' => Baogg_Language::get ( 'basic_info' ), 'index_p' => '0', 'xtype' => 'fieldset' );
		foreach ( ( array ) $arr_field as $k => $v ) {
			
			$index_p = 'container_' . floor ( $k / 2 );
			if ($k % 2 == 0) {
				$margins = '0 0 0 0';
				$arr_sql_filter [$index_p] = array ('id' => $index_p, 'fieldLabel' => '', 'index_p' => 'basic_info', 'layout' => 'hbox', 'xtype' => 'container' );
			} else {
				$margins = '0 0 0 30';
			}
			
			$str_url = BAOGG_BASE_URL . 'common/dict/qastore/qa_field_id/' . $v ['qa_field_id'];
			$arr_sql_filter [$v ['qa_field_code']] = array ('id' => $v ['qa_field_code'], "fieldLabel" => ($v ['qa_field_name'] ? $v ['qa_field_name'] : null), 'index_p' => $index_p, 'margins' => $margins, 			// 'store'=>$instance->getColCombo(array(),array(),array(),array($v['field_name'])),
			'width'=>380, 'hideTrigger' => false, 'mode' => 'remote', 'queryMode' => 'remote', 'minChars' => 1, 'valueField' => $v ['qa_field_code'], 'displayField' => 'text', 'xtype' => 'combo', 'forceSelection' => false, 'allowBlank' => true, 
			'listeners' => array ('expand' => new Zend_Json_Expr ( 'function(self,opts){var v=this.getValue();this.clearValue(); this.getStore().proxy.extraParams=form.getForm().getFieldValues();this.getStore().load({params:form.getForm().getFieldValues(),callback: function(records, operation, success) {this.expand();this.setValue(v);},scope:this});}' ) ), 'store' => new Zend_Json_Expr ( 'new Ext.data.JsonStore({root: "data",totalProperty: "count",idProperty: "' . $v ['qa_field_code'] . '",remoteSort: true,fields: ["' . $v ['qa_field_code'] . '","text"],autoLoad:false,proxy: new Ext.data.HttpProxy({type:"ajax",actionMethods: { create : "POST", read : "POST", update : "POST", destroy: "POST" }, reader: {	 type: "json", 	 totalProperty: "count", root: "data"},url: "' . $str_url . '"})})' ), 'pageSize' =>100 ); // ,"'.$item['displayField'].'"  Baogg_View_Extgrid::$PAGE_SIZE
				                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
			// $QaField->genFilterByFilterID ( $v ['qa_field_id'] );
		}
		
		$arr_sql_filter ['brand_info'] = array ('id' => 'brand_info', 'fieldLabel' => Baogg_Language::get ( 'brand_info' ), 'index_p' => '0', 'xtype' => 'fieldset' );
		$arr_sql_filter ['brand_rule'] = array ('id' => 'brand_rule', 'fieldLabel' => '', 'index_p' => 'brand_info', 'layout' => 'hbox', 'xtype' => 'container' );
		// echo '<pre>';print_r($store_brand);exit;
		$arr_sql_filter ['qa_brand_id'] = array ('id' => 'qa_brand_id', 'fieldLabel' => Baogg_Language::get ( 'qa_brand_id' ), 'index_p' => 'brand_rule', 'width'=>380,'labelWidth' => 100, 'xtype' => 'combo', 'store' => $QaField->addComboAll2 ( $QaBrand->getCombo ( array ('qa_surveys_id' => $qa_surveys_id, 'qa_brand_id' => $arr_qa_brand_ids ), array ('sort' => 'ordering', 'dir' => 'asc' ) ) ) );
		
		$arr_sql_filter ['qa_rule_id'] = array ('id' => 'qa_rule_id', 'fieldLabel' => Baogg_Language::get ( 'qa_rule_id' ), 'index_p' => 'brand_rule', 'width'=>380,'labelWidth' => 100, 'margins' => '0 0 0 30', 'xtype' => 'combo', 'store' => $QaField->addComboAll2 ( $QaRule->getCombo ( array ('qa_surveys_id' => $qa_surveys_id, 'qa_rule_id' => $arr_qa_rule_ids ), array ('sort' => 'ordering', 'dir' => 'asc' ) ) ) );
		
		$form->addItems ( $arr_sql_filter );
		
		$form->addExistButtons ( array ('search1', '-', 'cancel' ) ); // ,'config','config'
		
		$this->view->form = $form;
		$this->view->is_post = $post ? true : false;
		$form_url ['action'] = 'data2';
		$this->view->target_url = Baogg_Controller_Url::generate ( $form_url );
	}
	public function data2Action() {
		/*
		 * echo '<pre>' . __FILE__ . __LINE__; print_r ( $this->getRequest
		 * ()->getParams () ); exit ();
		 */
		global $LANG;
		
		$params = $this->getRequest ()->getParams ();
		$post = $this->getRequest ()->getPost ();
		
		isset ( $params ['qa_report_id'] ) or die ( 'No report params' );
		if (! isset ( $post ['qa_brand_id'] ) || ! isset ( $post ['qa_rule_id'] )) {
			echo '&nbsp;';
			exit;
		}
		$chart_url = $form_url = $params;
		
		Baogg_Language::loadFile ( 'qaquestion' );
		Baogg_Language::loadFile ( 'brandrule' );
		
		
		
	
		
		
		$Rule = new Rule ();
		
		$rs_qa_report = $this->QaReport->getOne ( $params ['qa_report_id'] );
		$arr_qa_field_ids = explode ( ',', $rs_qa_report [0] ['qa_field_ids'] );
		$arr_qa_brand_ids = explode ( ',', $rs_qa_report [0] ['qa_brand_ids'] );
		$arr_qa_rule_ids = explode ( ',', $rs_qa_report [0] ['qa_rule_ids'] );
		$qa_surveys_id = $rs_qa_report [0] ['qa_surveys_id'];
		
		// filter brand,rule
		
		$rs_qasureys = $this->QaSurveys->getOne ( $qa_surveys_id );
		$sid = $rs_qasureys [0] ['sid'];
		
		// get data
		$rs_qa_surveys = $this->Qa_Surveys->getOne ( $sid );
		$language = @$rs_qa_surveys [0] ['language'];
		
		$arr_field_map = $this->Qa_Questions->genFieldMap ( $sid );
		Zend_Loader::loadFile ( 'question_attribute.php', 'config/qa/', true );
		$qtypes = getqtypelist ();
		
		$QaField = new QaField ();
		// get all fields
		$arr_field = $QaField->getArray ( array ('qa_surveys_id' => $qa_surveys_id, 'qa_field_id' => $arr_qa_field_ids ), array ('sort' => 'ordering', 'dir' => 'asc' ) );
		
		$QaBrand = new QaBrand ();
		$arr_qa_brand = $QaBrand->getList ( array ('qa_surveys_id' => $qa_surveys_id, 'qa_brand_id' => $arr_qa_brand_ids ), array ('sort' => 'ordering', 'dir' => 'asc' ) );
		
		$QaRule = new QaRule ();
		$arr_qa_rule = $QaRule->getList ( array ('qa_surveys_id' => $qa_surveys_id, 'qa_rule_id' => $arr_qa_rule_ids ), array ('sort' => 'ordering', 'dir' => 'asc' ) );
		
		
		$arr_col_show_text=array();//convert qa field text to show text;
		// gen field map
		$cm = array ();
		
		$cm ['qa_fields'] = array ('header' => 'KPI指数分析' );
		foreach ( ( array ) $arr_field as $v_field ) {
			
			$field_code = $v_field ['qa_field_code'];
			
			if (! ($this->getRequest ()->isPost () && isset ( $post [$field_code] ) && trim ( $post [$field_code] ) !== "")) {
				continue;
			}
			/*
			 * if(trim($post [$field_code])=='#ALL#'){ $post [$field_code]=''; }
			 */
			
			$cm [$field_code] = array ('header' => $v_field ['qa_field_name'], 'PID' => 'qa_fields', 'width' => 80, 'suspendLayout' => true, 'resizable' => false );
			
			$arr_col_show_text [$field_code]=$QaField->genFilterTextByFilterID($v_field ['qa_field_id'],$arr_field_map,$qtypes);
		}
		$json_rule = array ();
		foreach ( ( array ) $arr_qa_brand as $v_brand ) {
			
			$rule_flag = false;
			
			if (! $post || $post ['qa_brand_id'] != '' && $post ['qa_brand_id'] != '#ALL#' && $v_brand ['qa_brand_id'] != $post ['qa_brand_id']) {
				continue;
			}
			
			foreach ( ( array ) $arr_qa_rule as $v_rule ) {
				
				if (! $post || $post ['qa_rule_id'] != '' && $post ['qa_rule_id'] != '#ALL#' && $v_rule ['qa_rule_id'] != $post ['qa_rule_id']) {
					continue;
				}
				
				$rs_rule = $Rule->getList ( array ('qa_brand_id' => $v_brand ['qa_brand_id'], 'qa_rule_id' => $v_rule ['qa_rule_id'] ) );
				if ($rs_rule) {
					$rule_flag = true;
					$cm ['rule_id_' . $rs_rule [0] ['rule_id']] = array ('header' => $v_rule ['qa_rule_name'], 'width' => 80, 'suspendLayout' => true, 'resizable' => false, 'PID' => 'qa_brand_id_' . $v_brand ['qa_brand_id'] ); //
					$json_rule [$rs_rule [0] ['rule_id']] = array ('qa_brand_id' => $v_brand ['qa_brand_id'], 'qa_rule_id' => $v_rule ['qa_rule_id'] );
				}
			}
			if ($rule_flag) {
				$cm ['qa_brand_id_' . $v_brand ['qa_brand_id']] = array ('header' => $v_brand ['qa_brand_name'] );
			}
		}
		
		// && !$is_group_by_list
		
		if (isset ( $cm ['id'] )) {
			$cm ['id'] = array ("hidden" => true, "cmType" => Baogg_View_Extgrid::CMTYPE_PK );
		}
		$grid = new Baogg_View_Grid ( $form_url, $cm );
		$cm_header = $grid->getCm ();
		
		
		//get data;
		$Rule = new Rule ();
		$arr_rule_id = array ();
		$arr_rule = array ();
		
		$arr_cols = array (); // all cols
		$arr_group_by_list = array ();
		
		$where = array ();
		
		foreach ( ( array ) $cm_header ['qa_fields'] ['columns'] as $v ) {
			$field_code = $v ['dataIndex'];
			$field_name = $v ['header'];
			
			if (trim ( $post [$field_code] ) == '#ALL#') {
				$post [$field_code] = '';
			}
			
			$where [$field_code] = $post [$field_code];
			$arr_group_by_list [] = $field_code;
			$arr_cols [$field_code] = $field_code;
			$arr_list_label [$field_code] = $field_name;
		
		}
		
		foreach ( ( array ) $cm_header as $parent_col => $fields ) {
			if (strpos ( $parent_col, 'qa_brand_id_' ) !== 0) {
				continue;
			}
			
			foreach ( ( array ) $fields ['columns'] as $v ) {
				if (strpos ( $v ['dataIndex'], 'rule_id_' ) !== 0) {
					continue;
				}
				
				$qa_rule_id = ( int ) substr ( $v ['dataIndex'], strlen ( 'rule_id_' ) );
				
				$rs_rule = $Rule->getOne ( $qa_rule_id );
				if ($rs_rule) {
					$arr_cols ['rule_id_' . $rs_rule [0] ['rule_id'] . '_2'] = new Zend_Db_Expr ( $rs_rule [0] ['compile_sql'] );
				}
			}
		}
		
		$where = array_filter ( $where );
		// echo '<pre>'.__FILE__.__LINE__;print_r($where);exit;
		// $order = $QaField->genOrderByReport ( $params ['qa_report_id'] );
		$limit = array ();
		$order = array ();
		foreach ( ( array ) $post as $k => $v ) {
			if ($k == "start" || $k == "limit") {
				$limit [$k] = $v;
			} else if ($k == "sort" || $k == "dir") {
				$order [$k] = $v;
			}
		}
		
		$Qa_Survey = new Qa_Survey ( $sid );
		
		//added extray filter
		$where[]="submitdate is not null";
		$rs = $Qa_Survey->getList ( $where, $order, $limit, $arr_cols, array (), $arr_group_by_list );
		
		$rule_path = BAOGG_UPLOAD_DIR . 'rule/';
		$array_sum = create_function ( '$array,$key', '$total = 0; foreach($array as $row) $total = $total + $row[$key]; return $total;' );
		
		// echo __FILE__.__LINE__.'<pre>';print_r($rs);print_r($arr_cols);exit;
		
		foreach ( ( array ) $rs as $k => $v ) {
			foreach ( $v as $col => $val ) {
				$rs [$k] [$col] = $val = isset($arr_col_show_text [$col][$val])?$arr_col_show_text [$col][$val]:$val;// $this->getValueByCol ( $col, $val, $qtypes, $arr_field_map, $language );
				
				if (preg_match ( '/^rule\_id\_(\d+)\_2$/', $col, $matches )) {
					$rule_id = $matches [1];
					$v ['rule_id_' . $rule_id] = $rs [$k] ['rule_id_' . $rule_id] = $rs [$k] [$col];
					if (! isset ( $arr_rule [$rule_id] )) {
						$rs_rule = $Rule->getOne ( $rule_id );
						$arr_rule [$rule_id] = @$rs_rule [0];
					}
					
					if ($arr_rule [$rule_id] ['compile']) {
						
						$rs [$k] ['rule_id_' . $rule_id] = @include $rule_path . $rule_id . '.php';
					
					}
				}
				/*
				 * if (isset ( $arr_list_label [$col] )) { $v [$arr_list_label
				 * [$col]] = $val; }
				 */
			
			}
		
		}
		
		/*
		 * echo '<pre>' . __FILE__ . __LINE__; print_r ( $cm_header ); exit ();
		 */
		$grid="<table border='1'><thead>";
		$arr_end_brand=end($cm_header);
		$is_no_brand=$arr_end_brand['header']=='所有品牌';
		//echo '<pre>' . __FILE__ . __LINE__; print_r ( $cm_header );var_dump ( $is_no_brand ); exit ();
		if(!$is_no_brand){
			$grid.="<tr>";		
			foreach ( $cm_header as $v_group ) {
				if (isset ( $v_group ['columns'] ) && is_array ( $v_group ['columns'] )) {
					$colspan = count ( $v_group ['columns'] );
					$grid.= "<th colspan='{$colspan}'>{$v_group['header']}</th>";
				} else {
					$grid.= "<th rowspan='2'>{$v_group['header']}</th>";
				}
			}
			$grid.="</tr>";
		}
		$grid.= '<tr>';
		
		foreach ( $cm_header as $v_group ) {
			
			foreach ( ( array ) $v_group ['columns'] as $v_cols ) {
				$grid.= '<th>' . $v_cols ['header'] . '</th>';
			}
		}
		$grid.= '</tr></thead>';
		
		//if cell value is same as above,then using rowspan
		$preview_row=array();//store preview value
		foreach ( ( array ) $rs as $index=>$row ) {
			$grid.= '<tr>';
			foreach ( $cm_header as $v_group ) {
				foreach ( ( array ) $v_group ['columns'] as $v_cols ) {
					$v_col=$v_cols ['dataIndex'];
					
					if(strpos($v_col,'rule_id_')===0){
						$row [$v_col]=round($row [$v_col],1);
						$grid.= "<td> {$row [$v_col]} &nbsp; </td>";
					}else{
						if(!isset($preview_row[$v_col]) || $preview_row[$v_col]!= $row [$v_col] ){
							for($i=1;;$i++){
								if(isset($rs[$index+$i]) && $rs[$index+$i][$v_col]==$row [$v_col]){
									
								}else{
									break;
								}
							}
							$rowspan=$i>1?" rowspan='{$i}'":'';
							$grid.= "<td {$rowspan}  class=\"label\"> {$row [$v_col]} &nbsp; </td>";						
						}
					}
					
				}
			}
			$preview_row=$row;
			$grid.= '</tr>';
		}
		$grid.= '</table>';
		$this->view->grid=$grid;
		//Zend_Controller_Front::getInstance ()->setParam ( 'noViewRenderer', true );
	}
	
	/**
	 * The default action
	 */
	public function listAction() {
		global $LANG;
		
		$params = $this->getRequest ()->getParams ();
		$post = $this->getRequest ()->getPost ();
		
		isset ( $params ['qa_report_id'] ) or die ( 'No report params' );
		$chart_url = $form_url = $params;
		
		Zend_Loader::loadClass ( "Baogg_View_Extgrid" );
		Baogg_Language::loadFile ( 'qaquestion' );
		Baogg_Language::loadFile ( 'brandrule' );
		
		$Rule = new Rule ();
		
		$rs_qa_report = $this->QaReport->getOne ( $params ['qa_report_id'] );
		$arr_qa_field_ids = explode ( ',', $rs_qa_report [0] ['qa_field_ids'] );
		$arr_qa_brand_ids = explode ( ',', $rs_qa_report [0] ['qa_brand_ids'] );
		$arr_qa_rule_ids = explode ( ',', $rs_qa_report [0] ['qa_rule_ids'] );
		$qa_surveys_id = $rs_qa_report [0] ['qa_surveys_id'];
		
		// filter brand,rule
		
		$rs_qasureys = $this->QaSurveys->getOne ( $qa_surveys_id );
		$sid = $rs_qasureys [0] ['sid'];
		
		$QaField = new QaField ();
		// get all fields
		$arr_field = $QaField->getArray ( array ('qa_surveys_id' => $qa_surveys_id, 'qa_field_id' => $arr_qa_field_ids ), array ('sort' => 'ordering', 'dir' => 'asc' ) );
		
		$QaBrand = new QaBrand ();
		$arr_qa_brand = $QaBrand->getList ( array ('qa_surveys_id' => $qa_surveys_id, 'qa_brand_id' => $arr_qa_brand_ids ), array ('sort' => 'ordering', 'dir' => 'asc' ) );
		
		$QaRule = new QaRule ();
		$arr_qa_rule = $QaRule->getList ( array ('qa_surveys_id' => $qa_surveys_id, 'qa_rule_id' => $arr_qa_rule_ids ), array ('sort' => 'ordering', 'dir' => 'asc' ) );
		
		// gen field map
		$cm = array ();
		
		foreach ( ( array ) $arr_field as $v_field ) {
			
			$field_code = $v_field ['qa_field_code'];
			
			if (! ($this->getRequest ()->isPost () && isset ( $post [$field_code] ) && trim ( $post [$field_code] ) !== "")) {
				continue;
			}
			/*
			 * if(trim($post [$field_code])=='#ALL#'){ $post [$field_code]=''; }
			 */
			
			$cm [$field_code] = array ('header' => $v_field ['qa_field_name'], 'width' => 80, 'suspendLayout' => true, 'resizable' => false, 'renderer' => new Zend_Json_Expr ( " function (value, meta, record, rowIndex, colIndex, store) {
                    var first = !rowIndex || value !== store.getAt(rowIndex - 1).get('{$field_code}'),
                        last = rowIndex >= store.getCount() - 1 || value !== store.getAt(rowIndex + 1).get('{$field_code}');
                    meta.css += 'row-span' + (first ? ' row-span-first' : '') +  (last ? ' row-span-last' : '');
                    if (first) {
                        var i = rowIndex + 1;
                        while (i < store.getCount() && value === store.getAt(i).get('{$field_code}')) {
                            i++;
                        }
                        var rowHeight = 20, padding = 6,
                            height = (rowHeight * (i - rowIndex) - padding) + 'px';
                        meta.attr = 'style=\"height:' + height + ';line-height:' + height + ';\"';
                    }
                    return first ? value : '';
                }" ) );
		}
		$json_rule = array ();
		foreach ( ( array ) $arr_qa_brand as $v_brand ) {
			
			$rule_flag = false;
			
			if (! $post || $post ['qa_brand_id'] != '' && $post ['qa_brand_id'] != '#ALL#' && $v_brand ['qa_brand_id'] != $post ['qa_brand_id']) {
				continue;
			}
			
			foreach ( ( array ) $arr_qa_rule as $v_rule ) {
				
				if (! $post || $post ['qa_rule_id'] != '' && $post ['qa_rule_id'] != '#ALL#' && $v_rule ['qa_rule_id'] != $post ['qa_rule_id']) {
					continue;
				}
				
				$rs_rule = $Rule->getList ( array ('qa_brand_id' => $v_brand ['qa_brand_id'], 'qa_rule_id' => $v_rule ['qa_rule_id'] ) );
				if ($rs_rule) {
					$rule_flag = true;
					$cm ['rule_id_' . $rs_rule [0] ['rule_id']] = array ('header' => $v_rule ['qa_rule_name'], 'width' => 80, 'suspendLayout' => true, 'resizable' => false, 'PID' => 'qa_brand_id_' . $v_brand ['qa_brand_id'] ); //
					$json_rule [$rs_rule [0] ['rule_id']] = array ('qa_brand_id' => $v_brand ['qa_brand_id'], 'qa_rule_id' => $v_rule ['qa_rule_id'] );
				}
			}
			if ($rule_flag) {
				$cm ['qa_brand_id_' . $v_brand ['qa_brand_id']] = array ('header' => $v_brand ['qa_brand_name'] );
			}
		}
		
		// && !$is_group_by_list
		
		if (isset ( $cm ['id'] )) {
			$cm ['id'] = array ("hidden" => true, "cmType" => Baogg_View_Extgrid::CMTYPE_PK );
		}
		
		$form_url ['action'] = "data";
		$grid = new Baogg_View_Extgrid ( $form_url, $cm );
		$grid->setSelectionModel ( true );
		$grid->setRowNumberer ( true );
		$grid->setStoreParams ( $post );
		
		$action_column = isset ( $cm ['id'] ) ? array ('report_view', 'delete' ) : array ();
		// var_dump($cm ['id'] );exit;
		$grid->addExistButtons ( array ('search' ), $action_column );
		
		$this->view->LANG = Zend_Json::encode ( $LANG );
		$this->view->grid = $grid->render ();
		$this->view->json_rule = Zend_Json::encode ( $json_rule );
		
		$form_url ['action'] = 'list';
		$form = new Baogg_View_Extform ( array ("url" => $form_url ), array (), array ('maximized' => true ) );
		
		$arr_sql_filter ['basic_info'] = array ('id' => 'basic_info', 'fieldLabel' => Baogg_Language::get ( 'basic_info' ), 'index_p' => '0', 'xtype' => 'fieldset' );
		foreach ( ( array ) $arr_field as $k => $v ) {
			
			$index_p = 'container_' . floor ( $k / 2 );
			if ($k % 2 == 0) {
				$margins = '0 0 0 0';
				$arr_sql_filter [$index_p] = array ('id' => $index_p, 'fieldLabel' => '', 'index_p' => 'basic_info', 'layout' => 'hbox', 'xtype' => 'container' );
			} else {
				$margins = '0 0 0 30';
			}
			
			$str_url = BAOGG_BASE_URL . 'common/dict/qastore/qa_field_id/' . $v ['qa_field_id'];
			$arr_sql_filter [$v ['qa_field_code']] = array ('id' => $v ['qa_field_code'], "fieldLabel" => ($v ['qa_field_name'] ? $v ['qa_field_name'] : null), 'index_p' => $index_p, 'margins' => $margins, 			// 'store'=>$instance->getColCombo(array(),array(),array(),array($v['field_name'])),
			'hideTrigger' => false, 'mode' => 'remote', 'queryMode' => 'remote', 'minChars' => 1, 'valueField' => $v ['qa_field_code'], 'displayField' => 'text', 'xtype' => 'combo', 'forceSelection' => false, 'allowBlank' => true, 'listeners' => array ('expand' => new Zend_Json_Expr ( 'function(event,opts){this.getStore().proxy.extraParams=form.getForm().getFieldValues();this.getStore().load({params:form.getForm().getFieldValues()});}' ) ), 'store' => new Zend_Json_Expr ( 'new Ext.data.JsonStore({root: "data",totalProperty: "count",idProperty: "' . $v ['qa_field_code'] . '",remoteSort: true,fields: ["' . $v ['qa_field_code'] . '","text"],autoLoad:false,proxy: new Ext.data.HttpProxy({type:"ajax",actionMethods: { create : "POST", read : "POST", update : "POST", destroy: "POST" }, reader: {	 type: "json", 	 totalProperty: "count", root: "data"},url: "' . $str_url . '"})})' ), 'pageSize' => Baogg_View_Extgrid::$PAGE_SIZE ); // ,"'.$item['displayField'].'"
				                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
			// $QaField->genFilterByFilterID ( $v ['qa_field_id'] );
		}
		
		$arr_sql_filter ['brand_info'] = array ('id' => 'brand_info', 'fieldLabel' => Baogg_Language::get ( 'brand_info' ), 'index_p' => '0', 'xtype' => 'fieldset' );
		$arr_sql_filter ['brand_rule'] = array ('id' => 'brand_rule', 'fieldLabel' => '', 'index_p' => 'brand_info', 'layout' => 'hbox', 'xtype' => 'container' );
		// echo '<pre>';print_r($store_brand);exit;
		$arr_sql_filter ['qa_brand_id'] = array ('id' => 'qa_brand_id', 'fieldLabel' => Baogg_Language::get ( 'qa_brand_id' ), 'index_p' => 'brand_rule', 'labelWidth' => 100, 'xtype' => 'combo', 'store' => $QaField->addComboAll2 ( $QaBrand->getCombo ( array ('qa_surveys_id' => $qa_surveys_id, 'qa_brand_id' => $arr_qa_brand_ids ), array ('sort' => 'ordering', 'dir' => 'asc' ) ) ) );
		
		$arr_sql_filter ['qa_rule_id'] = array ('id' => 'qa_rule_id', 'fieldLabel' => Baogg_Language::get ( 'qa_rule_id' ), 'index_p' => 'brand_rule', 'labelWidth' => 100, 'margins' => '0 0 0 30', 'xtype' => 'combo', 'store' => $QaField->addComboAll2 ( $QaRule->getCombo ( array ('qa_surveys_id' => $qa_surveys_id, 'qa_rule_id' => $arr_qa_rule_ids ), array ('sort' => 'ordering', 'dir' => 'asc' ) ) ) );
		
		$form->addItems ( $arr_sql_filter );
		
		$form->addExistButtons ( array ('search1', '-', 'cancel' ) ); // ,'config','config'
		
		$this->view->form = $form;
		$this->view->is_post = $post ? true : false;
	
	}
	
	/**
	 * The data action
	 */
	function dataAction() {
		global $LANG;
		
		BAOGG_LANGUAGE::loadFile ( 'qaquestion' );
		
		$post = $params = $this->getRequest ()->getParams ();
		
		// $post = $this->getRequest()->getPost ();
		// echo __FILE__.__LINE__.'<pre> <br
		// />';print_r($post);var_dump(!isset($post['qa_brand_id']) ||
		// !isset($post['qa_rule_id']));exit;
		if (! isset ( $post ['qa_brand_id'] ) || ! isset ( $post ['qa_rule_id'] )) {
			echo Zend_Json::encode ( array ("count" => 0, "data" => array () ) );
			Zend_Controller_Front::getInstance ()->setParam ( 'noViewRenderer', true );
			exit ();
		}
		
		isset ( $params ['qa_report_id'] ) or die ( 'No report params' );
		
		$rs_qa_report = $this->QaReport->getOne ( $params ['qa_report_id'] );
		$arr_qa_field_ids = explode ( ',', $rs_qa_report [0] ['qa_field_ids'] );
		$arr_qa_brand_ids = explode ( ',', $rs_qa_report [0] ['qa_brand_ids'] );
		$arr_qa_rule_ids = explode ( ',', $rs_qa_report [0] ['qa_rule_ids'] );
		$qa_surveys_id = $rs_qa_report [0] ['qa_surveys_id'];
		
		$rs_qasureys = $this->QaSurveys->getOne ( $qa_surveys_id );
		$sid = $rs_qasureys [0] ['sid'];
		
		$rs_qa_surveys = $this->Qa_Surveys->getOne ( $sid );
		$language = @$rs_qa_surveys [0] ['language'];
		
		$arr_field_map = $this->Qa_Questions->genFieldMap ( $sid );
		Zend_Loader::loadFile ( 'question_attribute.php', 'config/qa/', true );
		$qtypes = getqtypelist ();
		// echo '<pre>';print_r($arr_field_map);exit;
		
		// echo '<pre>';print_r($sid);exit;
		$QaField = new QaField ();
		$arr_field = $QaField->getArray ( array ('qa_surveys_id' => $qa_surveys_id, 'qa_field_id' => $arr_qa_field_ids ), array ("ordering" => "asc" ) );
		
		$Rule = new Rule ();
		$arr_rule_id = array ();
		$arr_rule = array ();
		
		$arr_cols = array (); // all cols
		$arr_group_by_list = array ();
		
		$where = array ();
		
		foreach ( ( array ) $arr_field as $v ) {
			$field_code = $v ['qa_field_code'];
			$field_name = $v ['qa_field_name'];
			// if field value is empty,then exit
			if (! ($this->getRequest ()->isPost () && isset ( $post [$field_code] ) && trim ( $post [$field_code] ) !== "")) {
				continue;
			}
			if (trim ( $post [$field_code] ) == '#ALL#') {
				$post [$field_code] = '';
			}
			
			$where [$field_code] = $post [$field_code];
			$arr_group_by_list [] = $field_code;
			$arr_cols [$field_code] = $field_code;
			$arr_list_label [$field_code] = $field_name;
		
		}
		
		foreach ( ( array ) $arr_qa_brand_ids as $qa_brand_id ) {
			if ($post ['qa_brand_id'] != '' && $post ['qa_brand_id'] != '#ALL#' && $qa_brand_id != $post ['qa_brand_id']) {
				continue;
			}
			foreach ( ( array ) $arr_qa_rule_ids as $qa_rule_id ) {
				
				if ($post ['qa_rule_id'] != '' && $post ['qa_rule_id'] != '#ALL#' && $qa_rule_id != $post ['qa_rule_id']) {
					continue;
				}
				
				$rs_rule = $Rule->getList ( array ('qa_brand_id' => $qa_brand_id, 'qa_rule_id' => $qa_rule_id ) );
				if ($rs_rule) {
					$arr_cols ['rule_id_' . $rs_rule [0] ['rule_id'] . '_2'] = new Zend_Db_Expr ( $rs_rule [0] ['compile_sql'] );
				}
			}
		}
		
		/*
		 * if ($this->getRequest ()->isPost () && isset ( $post ['field_op'] )
		 * && isset ( $post ['field_value'] )) { $rs_form_field =
		 * $QaField->getList ( array ('qa_report_id' => ( int ) $params
		 * ['qa_report_id'], 'is_filter' => 1 ) ); //echo
		 * __FILE__.'<pre>';print_r($rs_form_field);exit; foreach ( ( array )
		 * $rs_form_field as $v ) { $v ['operation'] = @$post ['field_op'] [$v
		 * ['qa_field_code']]; $v ['values'] = @$post ['field_value'] [$v
		 * ['qa_field_code']]; $where [] = $QaField->genFilter ( $v ); } } else
		 * { $where = $QaField->genFilterByReport ( $params ['qa_report_id'] );
		 * }
		 */
		$where = array_filter ( $where );
		// echo '<pre>';print_r($where);exit;
		// $order = $QaField->genOrderByReport ( $params ['qa_report_id'] );
		$limit = array ();
		$order = array ();
		foreach ( ( array ) $post as $k => $v ) {
			if ($k == "start" || $k == "limit") {
				$limit [$k] = $v;
			} else if ($k == "sort" || $k == "dir") {
				$order [$k] = $v;
			}
		}
		
		$Qa_Survey = new Qa_Survey ( $sid );
		
		$rs = $Qa_Survey->getList ( $where, $order, $limit, $arr_cols, array (), $arr_group_by_list );
		// if not column field,then 1
		if (! $arr_group_by_list) {
			$count = 1;
		} else {
			$rs_cnt = $Qa_Survey->getList ( $where, NULL, NULL, array (new Zend_Db_Expr ( "1" ) ), array (), $arr_group_by_list );
			$count = count ( $rs_cnt );
		}
		// echo
		// '<pre>';print_r($rs);print_r($rs_cnt);print_r($arr_group_by_list);exit;
		
		$rule_path = BAOGG_UPLOAD_DIR . 'rule/';
		$array_sum = create_function ( '$array,$key', '$total = 0; foreach($array as $row) $total = $total + $row[$key]; return $total;' );
		
		// echo __FILE__.__LINE__.'<pre>';print_r($rs);print_r($arr_cols);exit;
		foreach ( ( array ) $rs as $k => $v ) {
			foreach ( $v as $col => $val ) {
				$rs [$k] [$col] = $val = $this->getValueByCol ( $col, $val, $qtypes, $arr_field_map, $language );
				
				if (preg_match ( '/^rule\_id\_(\d+)\_2$/', $col, $matches )) {
					$rule_id = $matches [1];
					$v ['rule_id_' . $rule_id] = $rs [$k] ['rule_id_' . $rule_id] = $rs [$k] [$col];
					if (! isset ( $arr_rule [$rule_id] )) {
						$rs_rule = $Rule->getOne ( $rule_id );
						$arr_rule [$rule_id] = @$rs_rule [0];
					}
					
					/*
					 * $rs [$k] ['rule_id_101']=
					 * $v['rule_id_101']*100/$array_sum($rs,'rule_id_101');
					 * break;
					 */
					// only exist php code then use php
					if ($arr_rule [$rule_id] ['compile']) {
						
						$rs [$k] ['rule_id_' . $rule_id] = @include $rule_path . $rule_id . '.php';
					
					}
				}
				/*
				 * if (isset ( $arr_list_label [$col] )) { $v [$arr_list_label
				 * [$col]] = $val; }
				 */
			
			}
		
		}
		// echo __FILE__.__LINE__."<pre><br />";var_export($rs);exit;
		echo Zend_Json::encode ( array ("count" => $count, "data" => $rs ) );
		Zend_Controller_Front::getInstance ()->setParam ( 'noViewRenderer', true );
	}
	
	public function list1Action() {
		BAOGG_LANGUAGE::loadFile ( 'qaquestion' );
		
		$sid = $this->getRequest ()->getParam ( 'survey_id' );
		$sid = $this->getRequest ()->getParam ( 'id' );
		
		/*
		 * Check question type: This question types will be used (all others are
		 * separated in the if clause) 5 - 5 Point Choice G - Gender I -
		 * Language Switch L - List (Radio) M - Multiple Options N - Numerical
		 * Input O - List With Comment P - Multiple Options With Comments Y -
		 * Yes/No ! - List (Dropdown) )
		 */
		$Qa_Groups = new Qa_Groups ();
		
		$Qa_QuestionAttributes = new Qa_QuestionAttributes ();
		
		Zend_Loader::loadFile ( 'question_attribute.php', 'config/qa/', true );
		$qtypes = getqtypelist ();
		
		$rs_qa_surveys = $this->Qa_Surveys->getOne ( $sid );
		$language = @$rs_qa_surveys [0] ['language'];
		$Qa_SurveysLanguageSettings = new Qa_SurveysLanguageSettings ();
		$rs_qa_surveys_language_settings = $Qa_SurveysLanguageSettings->getList ( array ('surveyls_survey_id' => ( int ) $sid, 'surveyls_language' => $language ) );
		$survey_title = @$rs_qa_surveys_language_settings [0] ['surveyls_title'];
		
		$Qa_Survey = new Qa_Survey ( $sid );
		$rs_survey = $Qa_Survey->getOne ( $sid );
		$arr_survey = $rs_survey [0];
		
		$output = '';
		
		$output .= '<table id="main_content" class="data-entry-tbl" cellspacing="0"><thead><tr class="survey"><th colspan="2"><h3>' . $survey_title . '</h3></th></tr>';
		$i_row = 0;
		$output .= '<tr  class="question  row' . (++ $i_row % 2) . '" >';
		$output .= '<td>' . Baogg_Language::get ( 'id' ) . ":</td>";
		$output .= "<td>{$sid}</td>";
		$output .= "</tr>";
		
		$i_row = 0;
		$output .= '<tr  class="question  row' . (++ $i_row % 2) . '" >';
		$output .= '<td>' . Baogg_Language::get ( 'submitdate' ) . ":</td>";
		$output .= "<td>{$arr_survey['submitdate']}</td>";
		$output .= "</tr>";
		
		$rs_qa_groups = $Qa_Groups->getList ( array ('language' => $language, 'sid' => ( int ) $sid ), array ('sort' => 'group_order', 'dir' => 'asc' ), null, array ('gid', 'group_name', 'group_order' ) );
		foreach ( ( array ) $rs_qa_groups as $v_group ) {
			$output .= "<tr class=\"group\"><td  colspan=\"2\" class=\"row" . (++ $i_row % 2) . "\" style=\"width:100%; background-color: #F8F8FF;color: #1D2D45;\"><h3> {$v_group['group_name']}</h3></div></td></tr>";
			$rs_qa_questions = $this->Qa_Questions->getList ( array ('gid' => ( int ) $v_group ['gid'], 'parent_qid' => 0, 'LANGUAGE' => $language ), array ('sort' => 'question_order', 'dir' => 'asc' ) );
			foreach ( $rs_qa_questions as $v ) {
				$field_name = $_field_name = "{$sid}X{$v_group['gid']}X{$v['qid']}";
				$question_name = strip_tags ( $v ['question'] );
				
				$arr_field_map = array ();
				$arr_field_map += $this->Qa_Questions->genFieldMapByQuestion ( $v ['qid'] );
				
				$type = $v ['type'];
				$qid = $v ['qid'];
				
				if ($qtypes [$v ['type']] ['subquestions'] == 0 && $v ['type'] != "R") {
					
					$val = $this->getValueByCol ( $_field_name, $arr_survey [$_field_name], $qtypes, $arr_field_map, $language );
					$output .= '<tr  class="question  row' . (++ $i_row % 2) . '" ><td>' . strip_tags ( $v ['question'] ) . '</td><td>' . $val . '</td></tr>';
					
					switch ($v ['type']) {
						case "L" : // RADIO LIST
						case "!" : // DROPDOWN LIST
							if ($v ['other'] == "Y") {
								$_field_name = $field_name . "other";
								
								$val = $this->getValueByCol ( $_field_name, $arr_survey [$_field_name], $qtypes, $arr_field_map, $language );
								$output .= '<tr  class="question  row' . (++ $i_row % 2) . '" ><td>' . strip_tags ( $v ['question'] ) . ' - ' . Baogg_Language::get ( 'other' ) . '</td><td>' . $val . '</td></tr>';
							}
							break;
						case "O" : // DROPDOWN LIST WITH COMMENT
							$_field_name = $field_name . "comment";
							$val = $this->getValueByCol ( $_field_name, $arr_survey [$_field_name], $qtypes, $arr_field_map, $language );
							$output .= '<tr  class="question  row' . (++ $i_row % 2) . '" ><td>' . strip_tags ( $v ['question'] ) . ' - ' . Baogg_Language::get ( 'comment' ) . '</td><td>' . $val . '</td></tr>';
							break;
					}
				} else if ($qtypes [$type] ['subquestions'] == 2 && $qtypes [$v ['type']] ['answerscales'] == 0) {
					
					$output .= '<tr  class="question row' . (++ $i_row % 2) . '" >';
					$output .= '<td class="parent-question" colspan="2">' . $question_name . ":</td>";
					$output .= "</tr>";
					
					$rs_sub_question_y = $this->Qa_Questions->getList ( array ('parent_qid' => ( int ) $v ['qid'], 'language' => $language, 'scale_id' => 0 ), array ('sort' => 'question_order', 'dir' => 'asc' ) );
					$rs_sub_question_x = $this->Qa_Questions->getList ( array ('parent_qid' => ( int ) $v ['qid'], 'language' => $language, 'scale_id' => 1 ), array ('sort' => 'question_order', 'dir' => 'asc' ) );
					
					$output .= '<tr  class="question  row' . ($i_row % 2) . '" ><td colspan="2"><table>';
					$output .= '<tr  class="question  row' . ($i_row % 2) . '" ><td>&nbsp;</td>';
					foreach ( ( array ) $rs_sub_question_x as $v_sub_x ) {
						$output .= "<td>{$v_sub_x['question']}</td>";
					}
					$output .= "</tr>";
					
					foreach ( ( array ) $rs_sub_question_y as $v_sub_y ) {
						$output .= '<tr  class="question  row' . ($i_row % 2) . '" ><td>' . $v_sub_y ['question'] . '</td>';
						foreach ( ( array ) $rs_sub_question_x as $v_sub_x ) {
							$_field_name = $field_name . $v_sub_y ['title'] . "_" . $v_sub_x ['title'];
							$val = $this->getValueByCol ( $_field_name, $arr_survey [$_field_name], $qtypes, $arr_field_map, $language );
							$output .= "<td>{$val}</td>";
						}
						$output .= "</tr>";
					}
					$output .= "</table></td></tr>";
				} elseif ($qtypes [$v ['type']] ['answerscales'] == 2 && $qtypes [$v ['type']] ['subquestions'] == 1) {
					$rs_sub_question = $this->getList ( array ('parent_qid' => ( int ) $v ['qid'], 'language' => $language ), array ('sort' => 'question_order', 'dir' => 'asc' ) );
					$output .= '<tr  class="question  row' . (++ $i_row % 2) . '" ><td colspan="2"><table><tr class="question  row' . ($i_row % 2) . '"><td>&nbsp;</td><td>' . Baogg_Language::get ( '1' ) . '</td><td>' . Baogg_Language::get ( '2' ) . '</td><tr>';
					
					foreach ( $rs_sub_question as $v_sub ) {
						$output .= '<tr  class="question  row' . ($i_row % 2) . '" ><td>' . strip_tags ( $v_sub ['question'] ) . '</td>';
						
						$_field_name = $field_name . "{$v_sub['title']}#0";
						$val = $this->getValueByCol ( $_field_name, $arr_survey [$_field_name], $qtypes, $arr_field_map, $language );
						$output .= '<td>' . $val . '</td>';
						
						$_field_name = $field_name . "{$v_sub['title']}#1";
						$val = $this->getValueByCol ( $_field_name, $arr_survey [$_field_name], $qtypes, $arr_field_map, $language );
						$output .= '<td>' . $val . '</td>';
						
						$output .= "</tr>";
					}
					$output .= "</table></td></tr>";
				} elseif ($v ['type'] == "R") {
					// MULTI ENTRY
					$rs_answer = $this->Qa_Answers->getList ( array ('qid' => ( int ) $v ['qid'], 'language' => $language ), array ('sortorder', 'code' ) );
					$count = count ( $rs_answer );
					
					$output .= '<tr  class="question  row' . (++ $i_row % 2) . '" ><td style="text-align:left;" colspan="2">' . $question_name . '</td></tr>';
					for($i = 1; $i <= $count; $i ++) {
						$_field_name = $field_name . "$i";
						$val = $this->getValueByCol ( $_field_name, $arr_survey [$_field_name], $qtypes, $arr_field_map, $language );
						$output .= '<tr  class="question  row' . ($i_row % 2) . '" ><td>' . strip_tags ( $rs_answer [$i - 1] ['answer'] ) . '</td><td>' . $val . '</td></tr>';
					}
				
				} else if ($qtypes [$type] ['subquestions'] == 1) {
					
					$output .= '<tr  class="question  row' . (++ $i_row % 2) . '" ><td  class="parent-question" colspan="2">' . $question_name . ':</td></tr>';
					
					$rs_sub_question = $this->Qa_Questions->getList ( array ('parent_qid' => ( int ) $v ['qid'], 'language' => $language ), array ('sort' => 'question_order', 'dir' => 'asc' ) );
					foreach ( $rs_sub_question as $v_sub ) {
						$_field_name = $field_name . "{$v_sub['title']}";
						
						$val = $this->getValueByCol ( $_field_name, $arr_survey [$_field_name], $qtypes, $arr_field_map, $language );
						$output .= '<tr  class="question  row' . ($i_row % 2) . '" ><td>' . strip_tags ( $v_sub ['question'] ) . '</td><td>' . $val . '</td></tr>';
						if ($v ['type'] == "P") {
							$_field_name = $field_name . "{$v_sub['title']}comment";
							
							$val = $this->getValueByCol ( $_field_name, $arr_survey [$_field_name], $qtypes, $arr_field_map, $language );
							$output .= '<tr  class="question  row' . ($i_row % 2) . '" ><td>' . strip_tags ( $v_sub ['question'] ) . ' - ' . Baogg_Language::get ( 'comment' ) . '</td><td>' . $val . '</td></tr>';
						}
					}
					
					if ($v ['other'] == "Y" && ($v ['type'] == "M" || $v ['type'] == "P")) {
						$_field_name = $field_name . "other";
						$val = $this->getValueByCol ( $_field_name, $arr_survey [$_field_name], $qtypes, $arr_field_map, $language );
						$output .= '<tr  class="question  row' . ($i_row % 2) . '" ><td>' . strip_tags ( $v ['question'] ) . ' - ' . Baogg_Language::get ( 'other' ) . '</td><td>' . $val . '</td></tr>';
						
						if ($v ['type'] == "P") {
							$_field_name = $field_name . "othercomment";
							$val = $this->getValueByCol ( $_field_name, $arr_survey [$_field_name], $qtypes, $arr_field_map, $language );
							$output .= '<tr  class="question  row' . ($i_row % 2) . '" ><td>' . strip_tags ( $v ['question'] ) . ' - ' . Baogg_Language::get ( 'other' ) . ' - ' . Baogg_Language::get ( 'comment' ) . '</td><td>' . $val . '</td></tr>';
						
						}
					}
				}
			}
		}
		$output .= "</table>";
		$this->view->output = $output;
		
		// $this->_helper->viewRenderer->setNoRender ();
	}
	
	protected function getValueByCol($col, $val, $qtypes, $arr_field_map, $language) {
		$rs_k_col = $val;
		
		if (! isset ( $arr_field_map [$col] ) || in_array ( $arr_field_map [$col] ['type'], array ('id', 'submitdate' ) )) {
			return $rs_k_col;
		}
		
		$type = $arr_field_map [$col] ['type'];
		$qid = $arr_field_map [$col] ['qid'];
		$arr_answer = array (); // map qid=>(answer)code=>answer(text)
		
		if ($qtypes [$type] ['answerscales'] != 0) {
			if (! isset ( $arr_answer [$qid] )) {
				$rs_sub_answer = $this->Qa_Answers->getList ( array ('qid' => ( int ) $qid, 'language' => $language ), array ('sort' => 'sortorder', 'dir' => 'asc' ) );
				foreach ( $rs_sub_answer as $v_sub_answer ) {
					$arr_answer [$qid] [$v_sub_answer ['scale_id']] [$v_sub_answer ['code']] = $v_sub_answer ['answer'];
				}
			}
			$scale_id = isset ( $arr_field_map [$col] ['scale_id'] ) ? $arr_field_map [$col] ['qid'] : 0;
			isset ( $arr_answer [$qid] [$scale_id] [$val] ) && $rs_k_col = $arr_answer [$qid] [$scale_id] [$val];
		} else if (in_array ( $type, array ('G', 'Y', 'C', 'E' ) )) {
			$rs_k_col = Baogg_Language::get ( $val );
		} else if (in_array ( $type, array ('M', 'P' ) )) {
			// TODO
			$rs_qa_questions = $this->Qa_Questions->getList ( array ('parent_qid' => $qid, 'title' => $arr_field_map [$col] ['aid'] ) );
			if (! $rs_qa_questions) {
				// TODO exist ???
				return $rs_k_col;
			}
			/*
			 * echo
			 * __FILE__.__LINE__.'<pre>';var_dump($col);var_dump('X'.$rs_qa_questions[0]['parent_qid'].$rs_qa_questions[0]['title']);
			 * print_r($rs_qa_questions);exit;
			 */
			$suffix = 'X' . $rs_qa_questions [0] ['parent_qid'] . $rs_qa_questions [0] ['title'];
			if (substr ( $col, - strlen ( $suffix ) ) == $suffix) {
				if ($val == 'Y') {
					$rs_k_col = '<input type="checkbox" checked="checked" onclick="return false;"   />';
				} else if ($val === '') {
					$rs_k_col = '<input type="checkbox"  onclick="return false;" />';
				}
			}
		}
		
		return $rs_k_col;
	}
	
	public function data1Action() {
		global $LANG;
		
		BAOGG_LANGUAGE::loadFile ( 'qaquestion' );
		
		$params = $this->getRequest ()->getParams ();
		$post = $this->_request->getPost ();
		
		isset ( $params ['qa_report_id'] ) or die ( 'No report params' );
		
		$rs_qa_report = $this->QaReport->getOne ( $params ['qa_report_id'] );
		$sid = $rs_qa_report [0] ['survey_id'];
		$rs_qa_surveys = $this->Qa_Surveys->getOne ( $sid );
		$language = @$rs_qa_surveys [0] ['language'];
		
		$arr_field_map = $this->Qa_Questions->genFieldMap ( $sid );
		Zend_Loader::loadFile ( 'question_attribute.php', 'config/qa/', true );
		$qtypes = getqtypelist ();
		
		$QaField = new QaField ();
		// get all fields
		$arr_field = $QaField->getArray ( array ('qa_report_id' => $params ['qa_report_id'] ), array ('sort' => 'ordering', 'dir' => 'asc' ) );
		
		// get chart data
		$QaChart = new QaChart ();
		$rs_qa_chart = $QaChart->getList ( array ('qa_report_id' => $params ['qa_report_id'] ), array ('sort' => 'ordering', 'dir' => 'asc' ) );
		
		$arr_data_field = array (); // sql fn column,y axis
		$arr_group_field = array (); // group column, x axis
		
		$arr_data_label = array (); // chart title
		$arr_group_label = array (); // chart title
		
		$Rule = new Rule ();
		$arr_rule_id = array ();
		$arr_rule = array ();
		
		foreach ( ( array ) $rs_qa_chart as $v ) {
			
			$field_code = $arr_field [$v ['qa_field_id']] ['qa_field_code'];
			
			$col = $field_code;
			$val = $field_code;
			if ($v ['rule_id']) {
				
				if (! isset ( $arr_rule [$v ['rule_id']] )) {
					$rs_rule = $Rule->getOne ( $v ['rule_id'] );
					$arr_rule [$v ['rule_id']] = $rs_rule [0];
					
					// unset($rs_rule);
				}
				
				$col = $field_code . '__' . $v ['rule_id'];
				
				if (! $arr_rule [$v ['rule_id']] ['sql_fn']) {
					$val = $field_code;
				} else if (in_array ( $arr_rule [$v ['rule_id']] ['sql_fn'], array_keys ( Baogg_Language::get ( 'arr_mysql_func' ) ) )) {
					$val = new Zend_Db_Expr ( $arr_rule [$v ['rule_id']] ['sql_fn'] . '(' . $field_code . ')' );
				} else {
					$col_replace = array ('$col' => '`' . $field_code . '`' );
					foreach ( $arr_field as $field ) {
						$col_replace ['$v[\'' . $field ['qa_field_name'] . '\']'] = '`' . $field ['qa_field_code'] . '`';
					}
					// echo '<hr /><pre>';print_r($col_replace);echo
					// $arr_rule[$v['rule_id']]['sql_fn'];
					$val = new Zend_Db_Expr ( strtr ( $arr_rule [$v ['rule_id']] ['sql_fn'], $col_replace ) );
					
					// echo '<br />'.$val;
				}
				$arr_rule_id [$col] = $v ['rule_id'];
			}
			
			// if is group field
			if (! $v ['qa_chart_type']) {
				$arr_group_field [$col] = $val;
				$arr_group_label [$col] = $v ['qa_chart_name'];
			} else {
				$arr_data_field [$col] = $val;
				$arr_data_label [$col] = $v ['qa_chart_name'];
			}
		}
		
		$where = array ();
		if ($this->getRequest ()->isPost () && isset ( $post ['field_op'] ) && isset ( $post ['field_value'] )) {
			$rs_form_field = $QaField->getList ( array ('qa_report_id' => ( int ) $params ['qa_report_id'], 'is_filter' => 1 ) );
			// echo '<pre>';print_r($rs_form_field);exit;
			foreach ( ( array ) $rs_form_field as $v ) {
				$v ['operation'] = @$post ['field_op'] [$v ['qa_field_code']];
				$v ['values'] = @$post ['field_value'] [$v ['qa_field_code']];
				$where [] = $QaField->genFilter ( $v );
			}
		} else {
			$where = $QaField->genFilterByReport ( $params ['qa_report_id'] );
		}
		$where = array_filter ( $where );
		
		$order = $QaField->genOrderByReport ( $params ['qa_report_id'] );
		$limit = array ();
		$sid = $this->getRequest ()->getParam ( 'survey_id' );
		$Qa_Survey = new Qa_Survey ( $sid );
		$rs = $Qa_Survey->getList ( $where, $order, $limit, array_merge ( $arr_group_field, $arr_data_field ), array (), $arr_group_field );
		
		// echo __FILE__.'<pre>';print_r($arr_chart_col);exit;
		
		$rule_path = BAOGG_UPLOAD_DIR . 'rule/';
		$array_sum = create_function ( '$array,$key', '$total = 0; foreach($array as $row) $total = $total + $row[$key]; return $total;' );
		foreach ( ( array ) $rs as $k => $v ) {
			// convert float
			
			foreach ( $v as $col => $val ) {
				$rs [$k] [$col] = $val = $this->getValueByCol ( $col, $val, $qtypes, $arr_field_map, $language );
				
				if (isset ( $arr_group_label [$col] )) {
					$v [$arr_group_label [$col]] = $val;
				}
				
				if (isset ( $arr_data_label [$col] )) {
					$v [$arr_data_label [$col]] = $val;
				}
			}
			
			foreach ( $arr_rule_id as $col => $rule_id ) {
				
				// $rs[$k][$col]=(float)$rs[$k][$col];
				
				// $arr_rule_id=explode('__',$col);
				// $rule_id=end($arr_rule_id);
				
				if (@$arr_rule [$rule_id] ['compile']) {
					
					// echo
					// __FILE__.__LINE__.'<pre>';print_r($arr_data_field);print_r($arr_rule);var_dump($rule_id);var_dump($col);var_dump($array_sum($rs,$col));
					
					$rs [$k] [$col . '_2'] = @include $rule_path . $rule_id . '.php';
				}
			}
			
			// gen group field
			$col_group_field = implode ( '_', $arr_group_field );
			$val_group_name = array ();
			foreach ( $arr_group_field as $v_group_field ) {
				$val_group_name [] = $v [$v_group_field];
			}
			$rs [$k] [$col_group_field] = implode ( ' ', $val_group_name );
		
		}
		
		echo Zend_Json::encode ( array ("count" => count ( $rs ), "data" => $rs ) );
		Zend_Controller_Front::getInstance ()->setParam ( 'noViewRenderer', true );
	
	}
/**
 * The add action
 */
	/*
	 * function addAction() { $this->saveAction (); } function editAction() {
	 * $this->saveAction (); } function deleteAction() { $ret = array ("success"
	 * => false, "msg" => "delete_fail" ); $id =
	 * Baogg_Controller_Action::_getParam ( 'ids' ); $sid = $this->getRequest
	 * ()->getParam ( 'survey_id' ); $Qa_Survey = new Qa_Survey ( $sid ); if
	 * ($Qa_Survey->_delete ( $id )) { $ret ['success'] = true; $ret ["msg"] =
	 * "delete_ok"; } echo Baogg_Language::outputResult ( $ret );
	 * $this->_helper->viewRenderer->setNoRender (); } function removeAction() {
	 * $this->deleteAction (); } function saveAction() { //global $LANG; $ret =
	 * array ("success" => false, "msg" => "save_fail" ); //check form if (!
	 * $this->_request->isPost ()) { echo Baogg_Language::outputResult ( $ret );
	 * exit (); } $formData = $this->_request->getPost (); if (! $formData) {
	 * echo Baogg_Language::outputResult ( $ret ); exit (); } $arr =
	 * $this->QaReport->filterForm ( $formData ); $action = $this->getRequest
	 * ()->getParam ( 'action' ); $rs = $this->QaReport->getSame ( $arr ); if
	 * ($action == 'edit') { if (count ( $rs ) == 0 || count ( $rs ) == 1 && $rs
	 * [0] == $arr ["qa_report_id"]) { $this->QaReport->_update ( $arr, $arr
	 * ["qa_report_id"] ); $ret ['success'] = true; $ret ['msg'] = "save_ok"; }
	 * else { $ret ['msg'] = "exist_same_record"; } } else { //insert record
	 * //$permission_type = 1; if ($rs) { $ret ['msg'] = "exist_same_record"; }
	 * else { unset ( $arr ["qa_report_id"] ); $ret ['success'] =
	 * $this->QaReport->_insert ( $arr ) > 0 ? true : false; $ret ['msg'] =
	 * "add_ok"; } } echo Baogg_Language::outputResult ( $ret );
	 * $this->_helper->viewRenderer->setNoRender (); }
	 */

}
